<template>
  <div>
    <div class="trim flex-row">
      <span v-if="$store.state.type === 1"
        style="line-height: 32px;margin-right: 10px">所属城市</span>
      <el-select v-if="$store.state.type === 1"
        v-model="from.agentid" filterable default-first-option placeholder="--区域--"
        @change="getTableList()" style="margin-right: 40px">
        <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <span class="tag-price">账户余额：{{tableData.balance}}</span>
      <router-link style="margin-left: 100px" class="btn st1 flex-row-ver" tag='div' :to="{path: '/main/member/record', query: {id: from.agentid}}">
        <el-button type="primary">充值记录</el-button>
      </router-link>
      <el-button style="margin-left: 20px" type="primary" plain @click="openPay()">立即充值</el-button>
    </div>
    <el-row class="data-title">
      <el-col :span="8" class="item">外卖抽佣方式：{{tableData.waimaiway}}</el-col>
      <el-col :span="8" class="item">跑腿抽佣方式：{{tableData.paotuiway}}</el-col>
      <el-col :span="8" class="item">每月扣除下限：{{tableData.atLestPerMonth}}元</el-col>
      <el-col :span="8" class="item">开通系统日期：{{tableData.createTime}}</el-col>
      <el-col :span="8" class="item">余额不足告警：{{tableData.balancceWarning}}元</el-col>
    </el-row>
    <div class="base-table-wrap">
      <el-table :data="tableData.list" stripe style="width: 100%" v-loading>
        <el-table-column prop="date" label="账期" min-width="120" align="center" />
        <el-table-column prop="waimaichengjiao" :label="'外卖成交金额（'+comConfig.unit+'）'" min-width="120" align="center" />
        <el-table-column prop="paotuichengjiao" :label="'跑腿成交金额（'+comConfig.unit+'）'" min-width="120" align="center" />
        <el-table-column prop="waimaichouyog" :label="'外卖佣金（'+comConfig.unit+'）'" min-width="120" align="center" />
        <el-table-column prop="paotuichouyong" :label="'跑腿佣金（'+comConfig.unit+'）'" min-width="120" align="center" />
        <el-table-column prop="shijichouyong" :label="'实际佣金（'+comConfig.unit+'）'" min-width="120" align="center" />
        <el-table-column  label="操作" width="80" align="center" fixed="right">
          <template><el-button type="text" class="el-text-check">导出</el-button></template>
        </el-table-column>
      </el-table>
      <div class="base-directives-loading" v-show="isloadingTable">
        <div class="el-loading-spinner">
          <svg viewBox="25 25 50 50" class="circular">
            <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
          </svg>
        </div>
      </div>
    </div>
    <div class="base-pagination clearfix">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="newPage" :pageSize="pageSize" :page-sizes="[10, 20, 50, 100]" background
        layout="total,sizes, prev, pager, next, jumper" :total="tableData.total" />
    </div>
    <el-dialog v-dialogDrag :visible.sync="dialogTableVisible" :show-close="false" width="460px">
      <template slot="title">
        <div class="back-title" @click="dialogTableVisible = false">
          <i class="el-icon-arrow-left"></i><span>返回</span>
        </div>
      </template>
      <div class="pay-money" v-if="$store.state.type === 1">
        <div class="city">
          <div class="name">充值城市</div>
          <el-row type="flex">
            <el-select style="width: 100%" v-model="from.agentid" :disabled="true" size="large">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <!--<el-tooltip effect="dark" content="请在页面选择对应区域后充值" placement="top-start">
              <el-button type="text" icon="el-icon-question"></el-button>
            </el-tooltip>-->
          </el-row>
        </div>
        <el-row class="item" type="flex">
          <div class="title">充值金额</div>
          <input class="input-w" type="text" @blur="handleInput1" placeholder="实际支付的金额" v-model="from.chargemoney" />
        </el-row>
        <el-row class="item" type="flex">
          <div class="title">赠送金额</div>
          <input class="input-w" type="text" @blur="handleInput2" placeholder="额外赠送的金额" v-model="from.presentmoney" />
        </el-row>
        <el-button :loading="issubmitLoading" @click="payMoney()" class="btn-pay flex-row-ver">
          <span class="text">确认支付</span>
        </el-button>
      </div>
      <div class="pay-money" v-if="$store.state.type === 2 || $store.state.type === 3">
        <el-row class="item forat" type="flex">
          <div class="title">充值金额</div>
          <input class="input-w" type="text" @blur="handleInput1" placeholder="实际支付的金额" v-model="from.chargemoney" />
        </el-row>
        <el-button :loading="issubmitLoading" v-loading="payLoading" @click="payOhter(1)" class="pay-btn zfb flex-row-ver">
          <span class="text">支付宝支付</span>
        </el-button>
        <el-button :loading="issubmitLoading" v-loading="payLoading" @click="payOhter(2)" class="pay-btn wx flex-row-ver">
          <span class="text">微信支付</span>
        </el-button>
        <div class="act">
          <div class="met">
            温馨提示：
          </div>
          <p style="margin-bottom: 5px">账户余额仅为虚拟货币，可用于抵扣佣金，不会过期，但不能用转赠他人或提现；</p>
          <p style="margin-bottom: 5px">订单费固定为每笔0.2元，根据充值金额不同，有一定赠款；</p>
          <p style="margin-bottom: 5px">充值金额为：5999元以内，无赠款；</p>
          <p style="margin-bottom: 5px">充值金额为：6000元~11999元，赠款为充值金额的0.5倍，实际合算后最终每个订单费为0.15元；</p>
          <p style="margin-bottom: 5px">充值金额为：12000元以上，充多少赠多少，实际合算后最终每个订单费为0.1元；</p>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="微信扫码支付" v-dialogDrag :visible.sync="showWXerm" :close-on-press-escape="false" :close-on-click-modal="false" width="300px">
      <div class="erm-wrap flex">
        <pt-qrcode :qr-url='payQuery' :qr-size='200' :qr-logo-size="40" qr-logo="assets/img/wg-logo.png" />
        <el-button style="margin-top: 20px;" type="primary" plain @click="getPayStatus()">已支付</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { parseMoney } from '@/utils/ptkc.js'
  import { agentCharge, zfbChargeQuery, wxChargeQuery } from '@/api/member'
  export default {
    inject: ['upDateMoney'],
    data() {
      return {
        params: {
          page: 0,
          size: 10
        },
        issubmitLoading: false,
        isloadingTable: false,
        dialogTableVisible: false,
        payLoading: false, // 支付等待
        newPage: 1,
        tableData: {},
        pageSize: 10, //分页 数量
        from: {
          chargemoney: '',
          presentmoney: '',
          agentid: null
        },
        showWXerm: false, // 支付弹窗
        payQuery: '', // 生成的二维码
        wxOrderNo: '', // 微信支付的订单
      };
    },
    watch: {
      restaurants(val) {
        if (val.length) {
          this.from.agentid =val[0].id
          this.getTableList()
        }
      },
      'from.chargemoney': {
        handler(newValue, oldValue){
          this.from.chargemoney = newValue.replace(/[^\d.]/g,'')
        },
        deep: true
      },
      'from.presentmoney': {
        handler(newValue, oldValue){
          this.from.presentmoney = newValue.replace(/[^\d.]/g,'')
        },
        deep: true
      }
    },
    computed: {
      restaurants() { // 区域数据
        return this.$store.state.agentListArea
      },
      loginMsg() {
        const loginMsg = sessionStorage.getItem('loginMsg') || '{}'
        return JSON.parse(loginMsg)
      }
    },
    methods: {
      handleInput1() {
        this.from.chargemoney = parseMoney(this.from.chargemoney)
      },
      handleInput2() {
        this.from.presentmoney = parseMoney(this.from.presentmoney)
      },
      handleSizeChange(size) { // 设置分页数量
        this.params.size = size
        this.pageSize = size
        this.newPage = 1
        this.params.page = 0
        this.getTableList()
      },
      handleCurrentChange(page) { // 切换分页
        this.params.page = page - 1
        this.getTableList()
      },
      getTableList() {
        const params = { ...this.params }
        params.agentId = this.from.agentid
        this.isloadingTable = false
        this.$http.get("/server/HomePageController/MonthlyBill?" + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.tableData = res.data.data
            this.upDateMoney(this.tableData.balance)
          }
        }).finally(() => { this.isloadingTable = false })
      },
      payOhter(type) { // 支付宝、微信支付
        if (this.from.chargemoney <= 0 || this.from.chargemoney == ''|| !this.from.chargemoney) {
          this.$alert('请输入支付金额！~')
          return false
        }
        const returnUrl = window.location.href
        this.payLoading = true
        const params = { ...this.from }
        delete params.presentmoney
        delete params.agentid
        params.type = type
        params.returnUrl = returnUrl
        agentCharge(params).then(res => {
          if (res.success) {
            if (type === 1) {
              const div = document.createElement('div')
              // 此处form就是后台返回接收到的数据 唤起支付宝
              div.innerHTML = res.data.body
              document.body.appendChild(div)
              document.forms[0].submit()
            } else if (type === 2) {
              this.dialogTableVisible = false
              this.showWXerm = true
              this.payQuery = res.data.code_url
              this.wxOrderNo = res.data.orderNo
            }
          }
        }).finally(() => { this.payLoading = false })
      },
      openPay() { // 开始充值
        this.dialogTableVisible = true
        this.from.chargemoney= ''
        this.from.presentmoney= ''
      },
      getPayStatus() { // 查询微信支付状态
        wxChargeQuery({ orderno: this.wxOrderNo }).then(res => {
          if (res.success) {
            this.showWXerm = false
            let zs = ''
            if (this.from.chargemoney >= 6000 && this.from.chargemoney < 12000) zs = `,充值赠送${(this.from.chargemoney * 0.5).toFixed(2) +comConfig.unit}`
            else if (this.from.chargemoney >= 12000) zs = `,充值赠送${(this.from.chargemoney * 1).toFixed(2)}元`
            this.$alert(`您已成功充值${this.from.chargemoney +'元'+ zs}，请确认后查看！`, '微信支付结果!').then(() => {
              this.getTableList()
            })
          }
        })
      },
      payMoney() {
        const params = { ...this.from }
        this.issubmitLoading = true
        this.$http.post("/server/charge/charge" ,JSON.stringify(params)).then(res => {
          if (res.data.success) {
            this.$message.success('充值成功')
            this.getTableList()
            this.dialogTableVisible = false
          }
        }).finally(() => { this.issubmitLoading = false })
      }
    },
    mounted() {
      const query = this.$route.query
      if (query.out_trade_no && query.trade_no) {
        zfbChargeQuery({orderno: query.out_trade_no, trade_no: query.trade_no}).then(res => {
          if (res.success) {
            let zs = ''
            if (query.total_amount >= 6000 && query.total_amount < 12000) zs = `,充值赠送${(query.total_amount * 0.5).toFixed(2)}+元`
            else if (query.total_amount >= 12000) zs = `,充值赠送${(query.total_amount*1).toFixed(2)}元 `
            this.$alert(`您已成功充值${query.total_amount  +'元'+ zs}，请确认后查看！`, '支付宝充值结果!').then(() => {
              location.replace(window.location.href.split('?')[0])
              if (this.restaurants && this.restaurants.length) {
                this.from.agentid = this.restaurants[0].id
                this.getTableList()
              }
            })
          }
        })
      } else {
        if (this.restaurants && this.restaurants.length) {
          this.from.agentid = this.restaurants[0].id
          this.getTableList()
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  @import './css/info.scss';
</style>
